package com.cyt.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cyt.entity.GuanLI;

//Filter过滤器
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
     //doFilter是过滤器的核心方法,访问所有请求都会先经过该方法,所以只需要在该方法中判断用户有没有登录即可
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req =(HttpServletRequest)request;//将ServletRequest强转为HttpServletRequest
		HttpServletResponse res =(HttpServletResponse)response;//将ServletResponse强转为HttpServletResponse
		HttpSession session = req.getSession();//创建session对象
		GuanLI guan =(GuanLI)session.getAttribute("guan");//从session中获取guanli对象的值
		String url = req.getRequestURI();//获得访问的路径
		System.out.println(url);
		if(url.endsWith(".css")|| url.endsWith(".js")||url.endsWith(".jpg")) {
        	chain.doFilter(req, res);//放行

		}else if(url.indexOf("login.html")>0) {//代表访问登录页面
        	chain.doFilter(req, res);//放行
		}else {
			 if(guan!=null) {//登录过
		        	chain.doFilter(req, res);//放行
		        }else {//没登录过
		        	res.sendRedirect("login.html");
		        	
		        }

		}
		
		
       
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	

}
